'''
Author: duliang thinktanker@163.com
Date: 2025-09-27 19:57:28
LastEditors: duliang thinktanker@163.com
LastEditTime: 2025-09-28 18:51:25
Description: 服务器获取答案
'''
import sqlite3
import difflib
from typing import Optional, Tuple
import json
import os


class QuestionMatcher:
    def __init__(self, db_path: str):
        """
        初始化QuestionMatcher
        
        Args:
            db_path (str): 数据库文件路径
        """
        self.db_path = db_path

    def find_best_match(
            self,
            input_string: str,
            threshold: float = 0.01) -> Optional[Tuple[str, str, float]]:
        """
        在数据库中查找与输入字符串最匹配的问题及答案
        
        Args:
            input_string (str): 输入的待匹配字符串
            threshold (float): 匹配阈值，默认为0.6
            
        Returns:
            Optional[Tuple[str, str, float]]: (问题, 答案, 相似度) 或 None
        """
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()

            # 查询所有问题
            cursor.execute("SELECT questions, options, answers FROM tk")
            rows = cursor.fetchall()

            conn.close()

            if not rows:
                return None

            # 计算相似度并找出最佳匹配
            best_match = None
            best_similarity = 0.0

            for question, option, answer in rows:
                similarity = difflib.SequenceMatcher(None,
                                                     input_string.lower(),
                                                     question.lower()).ratio()
                if similarity > best_similarity and similarity >= threshold:
                    best_similarity = similarity
                    best_match = (question, answer, similarity)
                    # 如果option不是空，则显示key为answer的option内容
                    if option:
                        try:
                            option_dict = json.loads(option.replace("'", '"'))
                            if isinstance(option_dict,
                                          dict) and answer in option_dict:
                                answer = f"{answer}、{option_dict[answer]}"
                                # 更新best_match中的答案
                                best_match = (question, answer, similarity)
                        except json.JSONDecodeError as e:
                            print(f"JSON解析错误: {e}")
                            print(f"错误的option内容: {option}")
                            # 格式化输出错误位置附近的内容，帮助调试
                            error_pos = e.pos if hasattr(e, 'pos') else 0
                            start_pos = max(0, error_pos - 20)
                            end_pos = min(len(option), error_pos + 20)
                            context = option[start_pos:end_pos]
                            print(f"错误位置上下文: ...{context}...")
                            # 如果解析失败，保持原始answer，并可能记录日志

            return best_match

        except Exception as e:
            print(f"查询数据库时发生错误: {e}")
            return None

    def get_all_questions_with_answers(self) -> list:
        """
        获取所有问题和答案
        
        Returns:
            list: 包含(问题, 答案)元组的列表
        """
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()

            cursor.execute("SELECT question, answer FROM questions")
            rows = cursor.fetchall()

            conn.close()
            return rows

        except Exception as e:
            print(f"查询数据库时发生错误: {e}")
            return []


def main(input_text, _type):
    db_path = fr"D:\myGitee\word-to-database-question-bank\data\{_type}tk.db"
    if os.path.exists(db_path):
        # 示例用法
        matcher = QuestionMatcher(db_path)

        # 查找最匹配的答案
        result = matcher.find_best_match(input_text)

        if result:
            question, answer, similarity = result
            print(f"最匹配的问题: {question}")
            print(f"答案: {answer}")
            print(f"相似度: {similarity:.2f}")
            return f"{question}\n{answer}"
        else:
            print("未找到匹配的问题")
            return None
    else:
        print("数据库文件不存在")


# 使用示例
if __name__ == "__main__":
    input_text = "或动力作用下工作"
    print(main(input_text))
